package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.AfterSaleApplication;
import enum_var.AfterSaleType;
import enum_var.ApplicationStatus;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import service.AfterSaleApplicationService;
import service.impl.AfterSaleApplicationServiceImpl;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;


import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.*;

@WebServlet("/api/afterSale/*")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class AfterSaleApplicationServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule()) // 注册 Java 8 日期时间模块
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // 禁用时间戳格式，使用 ISO 格式（如 2024-05-20T15:30:00）;
    private final AfterSaleApplicationService applicationService = new AfterSaleApplicationServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            System.out.println(pathInfo);
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || "/".equals(pathInfo)) {
                // 获取筛选参数
                String status = request.getParameter("status");
                String type = request.getParameter("type"); // 新增：获取类型筛选参数
                AfterSaleType afterSaleType = null;
                if (type != null && !type.isEmpty()) {
                    afterSaleType = AfterSaleType.valueOf(type); // 转换为枚举类型
                }
                // 获取申请列表
                if ("CONSUMER".equals(role)) {
                    // 消费者只能查看自己的申请
                    List<AfterSaleApplication> applications;
                    // 根据是否有状态和类型参数，调用不同的查询方法
                    if (status != null && !status.isEmpty() && afterSaleType != null) {
                        ApplicationStatus applicationStatus = ApplicationStatus.valueOf(status);
                        applications = applicationService.getByUserIdStatusAndType(userId, applicationStatus, afterSaleType);
                    } else if (status != null && !status.isEmpty()) {
                        ApplicationStatus applicationStatus = ApplicationStatus.valueOf(status);
                        applications = applicationService.getByUserIdAndStatus(userId, applicationStatus);
                    } else if (afterSaleType != null) {
                        applications = applicationService.getByUserIdAndType(userId, afterSaleType);
                    } else {
                        applications = applicationService.getApplicationsByUserId(userId);
                    }
                    result.put("success", true);
                    result.put("data", applications);
                } else if ("CUSTOMER_SERVICE".equals(role)) {
                    // 客服查看待审核的申请
                    List<AfterSaleApplication> applications;
                    if (status != null && !status.isEmpty() && afterSaleType != null) {
                        ApplicationStatus applicationStatus = ApplicationStatus.valueOf(status);
                        applications = applicationService.getByStatusAndType(applicationStatus, afterSaleType);
                    } else if (status != null && !status.isEmpty()) {
                        ApplicationStatus applicationStatus = ApplicationStatus.valueOf(status);
                        applications = applicationService.getApplicationsByStatus(applicationStatus);
                    } else if (afterSaleType != null) {
                        applications = applicationService.getByType(afterSaleType);
                    } else {
                        applications = applicationService.getAllApplications();
                    }
                    result.put("success", true);
                    result.put("data", applications);
                } else {
                    throw new Exception("权限不足");
                }
            } else if (pathInfo.startsWith("/detail/")) {
                // 获取申请详情
                Long applicationId = Long.parseLong(pathInfo.substring(8));
                AfterSaleApplication application = applicationService.getApplicationById(applicationId);
                
                if (application == null) {
                    throw new Exception("申请不存在");
                }
                
                // 权限检查
                if ("CONSUMER".equals(role) && !application.getUserId().equals(userId)) {
                    throw new Exception("权限不足");
                }
                
                result.put("success", true);
                result.put("data", application);
            } else {
                throw new Exception("无效的请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");
            String productName = request.getParameter("productName");
            System.out.println(role);
            System.out.println(productName);
            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (!"CONSUMER".equals(role)) {
                throw new Exception("只有消费者可以提交售后申请");
            }

            // 解析请求参数
            Long orderId = Long.parseLong(request.getParameter("orderId"));
            AfterSaleType afterSaleType = AfterSaleType.valueOf(request.getParameter("afterSaleType"));
            String description = request.getParameter("description"); // 前端传递的description（修正参数名）

            // 处理文件上传（voucherFiles）
            List<String> voucherUrls = new ArrayList<>();
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                if ("voucherFiles".equals(part.getName())) { // 匹配前端的voucherFiles
                    String fileName = part.getSubmittedFileName();
                    if (fileName != null && !fileName.isEmpty()) {
                        // 此处需实现文件上传逻辑（如保存到服务器或云存储）
                        // 示例：假设上传后返回的URL为"/uploads/" + fileName
                        String fileUrl = "/uploads/" + fileName;
                        voucherUrls.add(fileUrl);
                        // 实际项目中需通过part.write()保存文件
                    }
                }
            }
            String voucherUrlsStr = String.join(",", voucherUrls); // 拼接为逗号分隔的URL字符串

            // 创建售后申请
            AfterSaleApplication application = new AfterSaleApplication();
            application.setUserId(userId);
            application.setProductName(productName);
            application.setOrderId(orderId);
            application.setAfterSaleType(afterSaleType);
            application.setVoucherUrls(voucherUrlsStr); // 设置文件URLs
            application.setStatus(ApplicationStatus.PENDING_AUDIT);
            application.setApplyTime(LocalDateTime.now());
            application.setApplyReason(description); // 用前端的description作为处理备注

            // 保存申请
            applicationService.createApplication(application);

            result.put("success", true);
            result.put("message", "申请提交成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }


    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            // 新增：处理消费者修改申请
            if (pathInfo != null && pathInfo.startsWith("/update/")) {
                // 权限检查：只有消费者可以修改自己的申请
                if (!"CONSUMER".equals(role)) {
                    throw new Exception("只有消费者可以修改申请");
                }

                Long applicationId = Long.parseLong(pathInfo.substring(8));
                AfterSaleApplication application = applicationService.getApplicationById(applicationId);

                // 验证申请存在且属于当前用户
                if (application == null) {
                    throw new Exception("申请不存在");
                }
                if (!application.getUserId().equals(userId)) {
                    throw new Exception("无权修改他人申请");
                }
                // 验证状态：只能修改待审核的申请
                if (application.getStatus() != ApplicationStatus.PENDING_AUDIT) {
                    throw new Exception("只能修改待审核的申请");
                }

                // 解析修改参数
                AfterSaleType afterSaleType = AfterSaleType.valueOf(request.getParameter("afterSaleType"));
                String description = request.getParameter("description");

                // 处理文件（保留原有文件，添加新文件）
                List<String> existingFiles = new ArrayList<>(Arrays.asList(
                        application.getVoucherUrls().split(",")));
                Collection<Part> parts = request.getParts();
                for (Part part : parts) {
                    if ("voucherFiles".equals(part.getName())) {
                        String fileName = part.getSubmittedFileName();
                        if (fileName != null && !fileName.isEmpty()) {
                            // 实际项目中需实现文件上传逻辑
                            String fileUrl = "/uploads/" + System.currentTimeMillis() + "_" + fileName;
                            existingFiles.add(fileUrl);
                        }
                    }
                }

                // 更新申请信息
                application.setAfterSaleType(afterSaleType);
                application.setApplyReason(description);
                application.setVoucherUrls(String.join(",", existingFiles));
                applicationService.updateApplication(application);

                result.put("success", true);
                result.put("message", "申请修改成功");
                out.write(objectMapper.writeValueAsString(result));
                return;
            }

            // 原有客服审核逻辑
            if (!"CUSTOMER_SERVICE".equals(role)) {
                throw new Exception("只有客服可以处理申请");
            }

            if (pathInfo == null || !pathInfo.startsWith("/audit/")) {
                throw new Exception("无效的请求路径");
            }

            Long applicationId = Long.parseLong(pathInfo.substring(7));
            String action = request.getParameter("action"); // approve, reject
            String reason = request.getParameter("reason");

            AfterSaleApplication application = applicationService.getApplicationById(applicationId);
            if (application == null) {
                throw new Exception("申请不存在");
            }

            if ("approve".equals(action)) {
                application.setStatus(ApplicationStatus.PROCESSING);
                application.setAuditTime(LocalDateTime.now());
                application.setHandleRemark(reason);
            } else if ("reject".equals(action)) {
                application.setStatus(ApplicationStatus.REJECTED);
                application.setAuditTime(LocalDateTime.now());
                application.setRejectReason(reason);
            } else {
                throw new Exception("无效的操作");
            }

            applicationService.updateApplication(application);

            result.put("success", true);
            result.put("message", "处理成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/cancel/")) {
                throw new Exception("无效的请求路径");
            }

            Long applicationId = Long.parseLong(pathInfo.substring(8));
            AfterSaleApplication application = applicationService.getApplicationById(applicationId);

            if (application == null) {
                throw new Exception("申请不存在");
            }

            // 只有申请人和客服可以取消申请
            if (!application.getUserId().equals(userId) && !"CUSTOMER_SERVICE".equals(role)) {
                throw new Exception("权限不足");
            }

            // 只有待审核状态的申请可以取消
            if (application.getStatus() != ApplicationStatus.PENDING_AUDIT) {
                throw new Exception("只能取消待审核的申请");
            }

            applicationService.deleteApplication(applicationId);

            result.put("success", true);
            result.put("message", "申请已取消");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }
}
